package logic

import (
	"context"
	"crypto/md5"
	"github.com/anaskhan96/go-password-encoder"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"time"
	"user/public"

	"user/internal/svc"
	"user/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserUpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserUpdatePasswordLogic {
	return &UserUpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 修改密码
func (l *UserUpdatePasswordLogic) UserUpdatePassword(in *user.UserUpdatePasswordRequest) (*user.UserUpdateLoginResponse, error) {
	// todo: add your logic here and delete this line
	//验参
	if in.Mobile == "" {
		return nil, status.Error(codes.FailedPrecondition, "Mobile is required")
	}
	if in.Password == "" {
		return nil, status.Error(codes.FailedPrecondition, "Password is required")
	}

	info := public.User{}

	//查询用户是否存在
	err := public.DB.Table("user").Where("user_mobile=?", in.Mobile).First(&info).Error
	if err != nil {
		return nil, status.Error(codes.InvalidArgument, "search mobile error  or user not find"+err.Error())
	}

	//验证加盐密码
	ok := public.CheckPassword(info.Salt, in.Password, info.UserSaltPassword)
	if !ok {
		return nil, status.Error(codes.InvalidArgument, " Incorrect password")
	}

	//盐值加密
	options := &password.Options{10, 10000, 50, md5.New}
	salt, encodedPwd := password.Encode(in.NewPassword, options)

	info.Salt = salt
	info.UserSaltPassword = encodedPwd
	info.UserPassword = in.NewPassword
	info.UpdTime = time.Now().Format("2006-01-02 15:04:05")
	//保存用户新的信息
	err = public.DB.Table("user").Save(&info).Error
	if err != nil {
		return nil, status.Error(codes.InvalidArgument, "save user info error"+err.Error())
	}

	return &user.UserUpdateLoginResponse{
		Status: info.UserName + "修改密码成功",
	}, nil
}
